package com.cdxy.aspect;

import com.cdxy.enums.redis.RedisCacheGroupEnum;
import com.cdxy.model.dto.base.redis.RedisCacheManager;
import com.cdxy.model.dto.base.resp.ApiResponse;
import com.cdxy.model.dto.resp.UserInfoResp;
import com.cdxy.util.JwtUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tangy
 * @Date: 2020/3/7 18:21
 */
@Aspect
@Component
public class TokenAspect {

    @Autowired
    private RedisCacheManager redisCacheManager;

    @Value("${auth.ax-user.private-key}")
    private String privateKey;

    @Value("${auth.ax-user.public-key}")
    private String publicKey;


    @Pointcut("@annotation(com.cdxy.aop.Token)")
    public void annotationPointcut() {
    }

    @AfterReturning(returning = "ret", pointcut = "annotationPointcut()")
    public void addToken(JoinPoint joinPoint, Object ret) {
        ApiResponse apiResponse = (ApiResponse) ret;
        UserInfoResp userInfoResp = (UserInfoResp) apiResponse.getData();
        Map<String, String> payload = initPayloadInfo(userInfoResp.getAxUid());
        String token = "";
        try {
            token = "Bearer " + JwtUtil.genToken(payload, privateKey);
            redisCacheManager.put(RedisCacheGroupEnum.LOGIN_SUCCESS_TOKEN, token, userInfoResp, 30 * 24 * 60 * 60);
        } catch (Exception e) {
            token = "";
        }
        userInfoResp.setToken(token);
    }


    private Map<String, String> initPayloadInfo(Integer axUid) {
        Map<String, String> payload = new HashMap<>(1);
        payload.put("AxUid", axUid.toString());
        return payload;
    }
}
